import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Select, Button, Typography, Tag, message } from 'antd';
import { 
  UserOutlined,
  CloseCircleOutlined
} from '@ant-design/icons';
import { Task } from '../models/taskModels';
import { createTask } from '../../../services/taskService';
import { getUserNames } from '../../../services/user';

const { Option } = Select;
const { TextArea } = Input;

export interface CreateTaskModalProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: () => void;
  username: string;
  parentId?: string;
}

/**
 * 新建任务弹窗组件
 */
const CreateTaskModal: React.FC<CreateTaskModalProps> = ({
  visible,
  onCancel,
  onSuccess,
  username,
  parentId
}) => {
  const [form] = Form.useForm();
  const [userOptions, setUserOptions] = useState<{ label: string; value: string }[]>([]);
  const [loadingUsers, setLoadingUsers] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  // 获取用户列表
  useEffect(() => {
    if (visible) {
      fetchUserNames();
      form.resetFields();
    }
  }, [visible, form]);

  // 获取用户名称列表
  const fetchUserNames = async () => {
    try {
      setLoadingUsers(true);
      const res = await getUserNames();
      if (res.code === 200 && res.data) {
        // 将后端返回的 "englishName/chineseName" 格式转换为下拉选项
        const options = res.data.map(item => {
          const [englishName, chineseName] = item.split('/');
          return {
            label: `${chineseName} (${englishName})`,
            value: item // 保存完整的 "englishName/chineseName" 字符串
          };
        });
        setUserOptions(options);
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
    } finally {
      setLoadingUsers(false);
    }
  };

  // 处理多选处理人
  const handleReceiversChange = (values: string[]) => {
    // 不需要在这里将列表转换为字符串，只保存列表值
    form.setFieldValue('receiver', values);
  };

  // 处理新建任务
  const handleCreateTask = async () => {
    try {
      setSubmitting(true);
      const values = await form.validateFields();
      
      // 将处理人数组转换为格式化的字符串
      const formattedReceiver = values.receiver && values.receiver.length > 0 
        ? values.receiver.join('|') 
        : undefined;
      
      // 创建任务数据对象
      const taskData: Partial<Task> = {
        ...values,
        receiver: formattedReceiver, // 使用格式化后的处理人字符串
        status: 'todo',
        creater: username,
        type: '暂无分类',  // 设置默认值
        subType: '暂无子分类', // 设置默认值
        level: '暂无', // 设置默认值
        parentId: parentId || undefined,
      };
      
      // 添加调试日志
      console.log('创建任务数据:', {
        formValues: values,
        taskData: taskData,
        parentId: parentId
      });
      
      const response = await createTask(taskData);
      
      if (response.code === 200) {
        message.success('创建任务成功');
        form.resetFields();
        onSuccess();
      } else {
        message.error('创建任务失败');
      }
    } catch (error) {
      console.error('创建任务失败:', error);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Modal
      title={<Typography.Title level={4}>新建任务</Typography.Title>}
      open={visible}
      onCancel={onCancel}
      // 设置弹窗宽度为视窗宽度的50%
      width="25vw"
      footer={
        <div className="flex justify-end gap-3">
          <Button onClick={onCancel}>取消</Button>
          <Button type="primary" loading={submitting} onClick={handleCreateTask}>创建</Button>
        </div>
      }
    >
      <Form form={form} layout="vertical">
        <Form.Item 
          name="title" 
          label="任务标题" 
          rules={[{ required: true, message: '请输入任务标题' }]}
        >
          <TextArea placeholder="请输入任务标题" allowClear autoSize={{ minRows: 4, maxRows: 6 }} />
        </Form.Item>
        
        <Form.Item
          name="receiver"
          label="处理人"
          tooltip="可选择多个处理人"
        >
          <Select
            mode="multiple"
            placeholder="请选择处理人"
            loading={loadingUsers}
            showSearch
            options={userOptions}
            filterOption={(input, option) => 
              option?.label?.toString().toLowerCase().includes(input.toLowerCase()) || false
            }
            onChange={handleReceiversChange}
            style={{ width: '100%' }}
            tagRender={(props) => {
              const { label, value, closable, onClose } = props;
              // 自定义标签渲染，实现单独删除功能
              return (
                <Tag 
                  className="mr-1 mb-1" 
                  closable={closable} 
                  onClose={onClose}
                  closeIcon={<CloseCircleOutlined className="ml-1" />}
                >
                  {label}
                </Tag>
              );
            }}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CreateTaskModal; 